<template>
  <div class="templatetable-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="24">
        <el-button :icon="Search" plain type="primary" @click="openQuery">
          查询
        </el-button>
        <el-button :icon="DocumentAdd" plain type="primary" @click="handleAdd">
          新增
        </el-button>
        <el-button
          :disabled="!currentRow"
          :icon="Edit"
          plain
          type="warning"
          @click="toUpdate()"
        >
          修改
        </el-button>
        <el-button
          :disabled="!currentRow"
          :icon="Delete"
          plain
          type="danger"
          @click="toDelete()"
        >
          删除
        </el-button>
        <el-button
          :disabled="!currentRow"
          :icon="Refresh"
          plain
          type="primary"
          @click="handleChangeRole"
        >
          角色变更
        </el-button>
        <el-button
          :disabled="!currentRow"
          :icon="Refresh"
          plain
          type="primary"
          @click="resetUserPassword()"
        >
          重置密码
        </el-button>
      </vab-query-form-left-panel>
    </vab-query-form>
    <el-row>
      <el-col :span="3">
        <el-tree
          :data="deptTree"
          highlight-current="true"
          node-key="pkDept"
          :props="{ children: 'downs', label: 'deptName' }"
          @node-click="handleTreeClick"
        />
      </el-col>
      <el-col :span="1" />
      <el-col :span="18">
        <el-table
          ref="userListTable"
          :data="userListDataSource"
          highlight-current-row
          @current-change="handleCurrentChange"
        >
          <el-table-column
            align="center"
            label="序号"
            type="index"
            width="80px"
          />
          <el-table-column label="用户编码" min-width="50" prop="userid" />
          <el-table-column label="用户名称" min-width="50" prop="name" />
          <el-table-column label="用户岗位" min-width="50" prop="position" />
          <el-table-column label="联系方式" min-width="100" prop="mobile" />
          <el-table-column label="用户邮箱" min-width="100" prop="bizMail" />
          <el-table-column label="用户地址" min-width="100" prop="address" />
        </el-table>
        <el-pagination
          background
          :current-page="paginationParams.pageNo"
          :layout="layout"
          :page-size="paginationParams.pageSize"
          :total="paginationParams.total"
          @current-change="handlePaginationCurrentChange"
          @size-change="handlePaginationSizeChange"
        />
      </el-col>
    </el-row>
    <UserAddModuleVue ref="userAddModule" @success-callback="getData" />
    <UserChangeRolesVue ref="userChangeRoles" @success-callback="getData" />
    <QueryDialogVue ref="queryDialogRef" @query-callback="queryCallback" />
  </div>
</template>
<script setup>
  import {
    Search,
    DocumentAdd,
    Delete,
    Edit,
    Refresh,
  } from '@element-plus/icons-vue'
  import {
    getUserPageApi,
    deleteUserApi,
    resetUserPasswordApi,
  } from '@/api/comdesk/user'
  import { getDeptTreeApi } from '@/api/base/dept'
  import UserAddModuleVue from './modules/UserAddModule.vue'
  import UserChangeRolesVue from './modules/UserChangeRoles.vue'
  import QueryDialogVue from './modules/queryDialog.vue'
  import { localStorageConfig } from '@/config/localstorage.config'

  const pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)

  const $baseMessage = inject('$baseMessage')

  const deptTree = ref([])
  const queryDialogRef = ref()
  const userAddModule = ref()
  const userChangeRoles = ref()
  const queryForm = reactive({})

  const getData = async () => {
    queryForm.pageNum = paginationParams.pageNo
    queryForm.pageSize = paginationParams.pageSize
    const res = await getUserPageApi(queryForm)
    if (res && res.code === 2000) {
      userListDataSource.value = res.data.list
      paginationParams.total = res.data.total
    } else {
      $baseMessage(res && res.msg ? res.msg : '获取失败,请重试', 'error')
    }
  }

  const openQuery = () => {
    queryDialogRef.value.openDialog()
  }

  const queryCallback = (query) => {
    queryForm.userid = query.userid
    queryForm.name = query.name
    queryForm.mobile = query.mobile
    getData()
  }

  const getDept = async () => {
    const res = await getDeptTreeApi({ pkCorp: pkCorp })
    if (res && res.code === 2000) {
      deptTree.value = res.data
    }
  }

  const handleTreeClick = (row) => {
    queryForm.pkDept = row.pkDept
    queryForm.downs = row.downs
    getData()
  }

  const layout = ref('total, sizes, prev, pager, next, jumper')
  const paginationParams = reactive({
    pageNo: 1,
    pageSize: 10,
    total: 0,
  })
  const handleAdd = () => {
    if (queryForm.downs && queryForm.downs.length === 0) {
      userAddModule.value.openDialog({ pkDept: queryForm.pkDept })
    } else {
      $baseMessage('请选择部门末级进下新增！', 'warning')
    }
  }
  const toUpdate = () => {
    userAddModule.value.openDialog(currentRow.value)
  }
  const handleChangeRole = () => {
    userChangeRoles.value.openUserChangeRolesDialog(currentRow.value)
  }
  const resetUserPassword = async () => {
    let params = { pkUser: currentRow.value.pkUser }
    const res = await resetUserPasswordApi(params)
    if (res && res.code === 2000) {
      $baseMessage('操作成功', 'success')
    } else {
      $baseMessage(res && res.msg ? res.msg : '操作失败,请重试', 'error')
    }
  }

  const toDelete = async () => {
    ElMessageBox.confirm('确定要删除该用户吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const res = await deleteUserApi({ pkRole: row.pkRole })
        if (res && String(res.code) === '2000') {
          $baseMessage(res && res.msg ? res.msg : '操作成功', 'success')
          getData()
        } else {
          $baseMessage(res && res.msg ? res.msg : '操作失败,请重试', 'error')
        }
      })
      .catch(() => {})
  }

  const userListTable = ref(null)
  const userListDataSource = ref([])

  const currentRow = ref()
  const handleCurrentChange = (row) => {
    currentRow.value = row
  }

  const handlePaginationCurrentChange = (...args) => {
    paginationParams.pageNo = args[0] ? args[0] : 1
  }
  const handlePaginationSizeChange = (...args) => {
    paginationParams.pageSize = args[0] ? args[0] : 10
    paginationParams.pageNo = 1
  }

  // ---- 钩子 ----
  onMounted(() => {
    getData()
    getDept()
  })
  watch(paginationParams, () => {
    getData()
  })
  // ---- 钩子 ----
</script>
